package com.kws.system.service.impl;

import java.util.*;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kws.common.core.domain.R;
import com.kws.common.security.auth.AuthUtil;
import com.kws.system.api.domain.SysRole;
import com.kws.system.domain.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.kws.common.core.constant.UserConstants;
import com.kws.common.core.exception.ServiceException;
import com.kws.common.core.utils.SpringUtils;
import com.kws.common.core.utils.StringUtils;
import com.kws.common.datascope.annotation.DataScope;
import com.kws.common.security.utils.SecurityUtils;
import com.kws.system.api.domain.SysUser;
import com.kws.system.domain.SysRoleDept;
import com.kws.system.domain.SysRoleMenu;
import com.kws.system.domain.SysUserRole;
import com.kws.system.mapper.SysRoleDeptMapper;
import com.kws.system.mapper.SysRoleMapper;
import com.kws.system.mapper.SysRoleMenuMapper;
import com.kws.system.mapper.SysUserRoleMapper;
import com.kws.system.service.ISysRoleService;

/**
 * 角色 业务层处理
 *
 * @author zhangyh
 */
@Service
public class SysRoleServiceImpl implements ISysRoleService {
    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysRoleMenuMapper roleMenuMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysRoleDeptMapper roleDeptMapper;


    /**
     * 根据条件分页查询角色数据
     *
     * @param role 角色信息
     * @return 角色数据集合信息
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<SysRole> selectRoleList(SysRole role) {
        return roleMapper.selectRoleList(role);
    }

    /**
     * 根据用户ID查询角色
     *
     * @param userId 用户ID
     * @return 角色列表
     */
    @Override
    public List<SysRole> selectRolesByUserId(Long userId) {
        List<SysRole> userRoles = roleMapper.selectRolePermissionByUserId(userId);
        List<SysRole> roles = selectRoleAll();
        for (SysRole role : roles) {
            for (SysRole userRole : userRoles) {
                if (role.getRoleId().longValue() == userRole.getRoleId().longValue()) {
                    role.setFlag(true);
                    break;
                }
            }
        }
        return roles;
    }

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectRolePermissionByUserId(Long userId) {
        List<SysRole> perms = roleMapper.selectRolePermissionByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (SysRole perm : perms) {
            if (StringUtils.isNotNull(perm)) {
                if (perm.getRoleKey() != null) {
                    permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
                }
            }
        }
        return permsSet;
    }

    /**
     * 查询所有角色
     *
     * @return 角色列表
     */
    @Override
    public List<SysRole> selectRoleAll() {
        return SpringUtils.getAopProxy(this).selectRoleList(new SysRole());
    }

    /**
     * 根据用户ID获取角色选择框列表
     *
     * @param userId 用户ID
     * @return 选中角色ID列表
     */
    @Override
    public List<Long> selectRoleListByUserId(Long userId) {
        return roleMapper.selectRoleListByUserId(userId);
    }

    /**
     * 通过角色ID查询角色
     *
     * @param roleId 角色ID
     * @return 角色对象信息
     */
    @Override
    public SysRole selectRoleById(Long roleId) {
        return roleMapper.queryRoleById(roleId);
    }

    /**
     * 校验角色名称是否唯一
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public boolean checkRoleNameUnique(SysRole role) {
        Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();
        SysRole info = roleMapper.checkRoleNameUnique(role.getRoleName());
        if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验角色权限是否唯一
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public boolean checkRoleKeyUnique(SysRole role) {
        Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId();
        SysRole info = roleMapper.checkRoleKeyUnique(role.getRoleKey());
        if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验角色是否允许操作
     *
     * @param role 角色信息
     */
    @Override
    public void checkRoleAllowed(SysRole role) {
        if (StringUtils.isNotNull(role.getRoleId()) && role.isAdmin()) {
            throw new ServiceException("不允许操作超级管理员角色");
        }
    }

    /**
     * 校验角色是否有数据权限
     *
     * @param roleIds 角色id
     */
    @Override
    public void checkRoleDataScope(Long... roleIds) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
            for (Long roleId : roleIds) {
                SysRole role = new SysRole();
                role.setRoleId(roleId);
                List<SysRole> roles = SpringUtils.getAopProxy(this).selectRoleList(role);
                if (StringUtils.isEmpty(roles)) {
                    throw new ServiceException("没有权限访问角色数据！");
                }
            }
        }
    }

    /**
     * 通过角色ID查询角色使用数量
     *
     * @param roleId 角色ID
     * @return 结果
     */
    @Override
    public int countUserRoleByRoleId(Long roleId) {
        return userRoleMapper.countUserRoleByRoleId(roleId);
    }

    /**
     * 新增保存角色信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertRole(SysRole role) {
        // 新增角色信息
        roleMapper.insertRole(role);
        return insertRoleMenu(role);
    }

    /**
     * 修改保存角色信息
     *
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateRole(UpdateRoleRq rq) {
        //校验角色名称是否已存在
        SysRole sysRole = roleMapper.queryRoleByRoleName(rq.getRoleName());
        if (null != sysRole) {
            throw new ServiceException("角色名称已存在");
        }
        // 修改角色信息
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("role_id", rq.getId());
        updateWrapper.set("role_name", rq.getRoleName());
        updateWrapper.set("role_description", rq.getRoleDescription());
        int update = roleMapper.update(null, updateWrapper);
        return update;
    }

    /**
     * 修改角色状态
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public int updateRoleStatus(SysRole role) {
        return roleMapper.updateRole(role);
    }

    /**
     * 修改数据权限信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int authDataScope(SysRole role) {
        // 修改角色信息
        roleMapper.updateRole(role);
        // 删除角色与部门关联
        roleDeptMapper.deleteRoleDeptByRoleId(role.getRoleId());
        // 新增角色和部门信息（数据权限）
        return insertRoleDept(role);
    }

    /**
     * 新增角色菜单信息
     *
     * @param role 角色对象
     */
    public int insertRoleMenu(SysRole role) {
        int rows = 1;
        // 新增用户与角色管理
        List<SysRoleMenu> list = new ArrayList<SysRoleMenu>();
        for (Long menuId : role.getMenuIds()) {
            SysRoleMenu rm = new SysRoleMenu();
            rm.setRoleId(role.getRoleId());
            rm.setMenuId(menuId);
            list.add(rm);
        }
        if (list.size() > 0) {
            rows = roleMenuMapper.batchRoleMenu(list);
        }
        return rows;
    }

    /**
     * 新增角色部门信息(数据权限)
     *
     * @param role 角色对象
     */
    public int insertRoleDept(SysRole role) {
        int rows = 1;
        // 新增角色与部门（数据权限）管理
        List<SysRoleDept> list = new ArrayList<SysRoleDept>();
        for (Long deptId : role.getDeptIds()) {
            SysRoleDept rd = new SysRoleDept();
            rd.setRoleId(role.getRoleId());
            rd.setDeptId(deptId);
            list.add(rd);
        }
        if (list.size() > 0) {
            rows = roleDeptMapper.batchRoleDept(list);
        }
        return rows;
    }

    /**
     * 通过角色ID删除角色
     *
     * @param roleId 角色ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteRoleById(Long roleId) {
        // 删除角色与菜单关联
        roleMenuMapper.deleteRoleMenuByRoleId(roleId);
        // 删除角色与部门关联
        roleDeptMapper.deleteRoleDeptByRoleId(roleId);
        return roleMapper.deleteRoleById(roleId);
    }

    /**
     * 批量删除角色信息
     *
     * @param roleIds 需要删除的角色ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteRoleByIds(Long[] roleIds) {
        for (Long roleId : roleIds) {
            checkRoleAllowed(new SysRole(roleId));
            checkRoleDataScope(roleId);
            SysRole role = selectRoleById(roleId);
            if (countUserRoleByRoleId(roleId) > 0) {
                throw new ServiceException(String.format("%1$s已分配,不能删除", role.getRoleName()));
            }
        }
        // 删除角色与菜单关联
        roleMenuMapper.deleteRoleMenu(roleIds);
        // 删除角色与部门关联
        roleDeptMapper.deleteRoleDept(roleIds);
        return roleMapper.deleteRoleByIds(roleIds);
    }

    /**
     * 取消授权用户角色
     *
     * @param userRole 用户和角色关联信息
     * @return 结果
     */
    @Override
    public int deleteAuthUser(SysUserRole userRole) {
        return userRoleMapper.deleteUserRoleInfo(userRole);
    }

    /**
     * 批量取消授权用户角色
     *
     * @param roleId  角色ID
     * @param userIds 需要取消授权的用户数据ID
     * @return 结果
     */
    @Override
    public int deleteAuthUsers(Long roleId, Long[] userIds) {
        return userRoleMapper.deleteUserRoleInfos(roleId, userIds);
    }

    /**
     * 批量选择授权用户角色
     *
     * @param roleId  角色ID
     * @param userIds 需要授权的用户数据ID
     * @return 结果
     */
    @Override
    public int insertAuthUsers(Long roleId, Long[] userIds) {
        // 新增用户与角色管理
        List<SysUserRole> list = new ArrayList<SysUserRole>();
        for (Long userId : userIds) {
            SysUserRole ur = new SysUserRole();
            ur.setUserId(userId);
            ur.setRoleId(roleId);
            list.add(ur);
        }
        return userRoleMapper.batchUserRole(list);
    }

    @Override
    public Page<SysRole> selectRoleListByName(Integer pageNum, Integer pageSize, String roleName) {
        Page<SysRole> page = new Page<>(pageNum, pageSize);
        return roleMapper.selectRoleListByName(page, roleName);
    }

    @Override
    public R createRole(CreateRoleRq rq) {
        SysRole sysRole = roleMapper.queryRoleByRoleName(rq.getRoleName());
        if (null != sysRole) {
            return R.fail("角色已存在");
        }
        SysRole sysRole1 = new SysRole();
        sysRole1.setRoleName(rq.getRoleName());
        sysRole1.setRoleType(rq.getRoleType());
        sysRole1.setRoleKey("common");
        sysRole1.setStatus("0");
        sysRole1.setDelFlag("0");
        sysRole1.setCreateBy(SecurityUtils.getStringUserId());
        sysRole1.setCreateTime(new Date());
        sysRole1.setUpdateBy(SecurityUtils.getStringUserId());
        sysRole1.setUpdateTime(new Date());
        sysRole1.setRoleDescription(rq.getRoleDescription());
        sysRole1.setRoleType("0");
        int insert = roleMapper.insertRole(sysRole1);
        if (1 == insert) {
//            //保存角色关联部门信息
//            SysRoleDept sysRoleDept = new SysRoleDept();
//            sysRoleDept.setRoleId(sysRole1.getRoleId());
//            sysRoleDept.setDeptId(rq.getDeptId());
//            int insert1 = roleDeptMapper.insert(sysRoleDept);
//            if (1 == insert1){
//                return R.ok();
//            }else {
//                return R.fail("新增角色信息失败");
//            }
            return R.ok();
        } else {
            return R.fail("新增角色信息失败");
        }
    }

    @Override
    @Transactional
    public R addUserRoleByRoleId(AddUserRoleRq rq) {
        if (CollectionUtil.isEmpty(rq.getUserIds())) {
            return R.fail("添加用户不能为空！");
        }
        rq.getUserIds().forEach(item -> {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(item);
            sysUserRole.setRoleId(rq.getRoleId());
            int insert = userRoleMapper.insert(sysUserRole);
            if (1 != insert) {
                throw new ServiceException("用户授权角色失败！");
            }
        });
        return R.ok();
    }

    @Override
    public R accreditRoleMenu(AccreditRoleMenuRq rq) {
        //根据角色ID删除所有关联菜单
        roleMenuMapper.deleteRoleMenuByRoleId(rq.getRoleId());
        List<SysRoleMenu> roleMenuList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(rq.getMenuIds())) {
            rq.getMenuIds().forEach(item -> {
                SysRoleMenu sysRoleMenu = new SysRoleMenu();
                sysRoleMenu.setRoleId(rq.getRoleId());
                sysRoleMenu.setMenuId(item);
                int insert = roleMenuMapper.insert(sysRoleMenu);
            });
        }
        return R.ok();
    }

    @Override
    public boolean accreditMenuById(CreateAccreditMenuRq rq) {
        if (CollectionUtil.isNotEmpty(rq.getMenuIdList())){
            rq.getMenuIdList().forEach(item -> {
                SysRoleMenu sysRoleMenu = new SysRoleMenu();
                sysRoleMenu.setRoleId(rq.getRoleId());
                sysRoleMenu.setMenuId(item);
                roleMenuMapper.insert(sysRoleMenu);
            });

        }
        return false;
    }

    @Override
    public List<SysUser> queryUserRoleByRoleId(Long roleId) {
        return roleMapper.queryUserRoleByRoleId(roleId);
    }

    /**
     * 获取当前商家角色
     * @return
     */
    @Override
    public Page<SysRole> queryMerchantRolePage(Integer pageNum ,Integer pageSize, String roleName) {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long companyId = sysUser.getCompanyId();
        Page<SysRole> page = new Page<>(pageNum, pageSize);
        return roleMapper.queryMerchantRolePage(page, roleName,companyId);
    }

    /**
     * 商家端-新增角色
     * @param rq
     * @return
     */
    @Override
    public Object merchantAdd(CreateMerchantRoleRq rq) {
        SysRole sysRole = roleMapper.queryRoleByRoleName(rq.getRoleName());
        if (null != sysRole) {
            return R.fail("角色已存在");
        }
        SysRole sysRole1 = new SysRole();
        sysRole1.setRoleName(rq.getRoleName());
        sysRole1.setRoleType("1");
        sysRole1.setRoleKey("common");
        sysRole1.setStatus("0");
        sysRole1.setDelFlag("0");
        sysRole1.setCreateBy(String.valueOf(SecurityUtils.getCompanyId()));
        sysRole1.setCreateTime(new Date());
        sysRole1.setUpdateBy(String.valueOf(SecurityUtils.getCompanyId()));
        sysRole1.setUpdateTime(new Date());
        sysRole1.setRoleDescription(rq.getRoleDescription());
        sysRole1.setRoleType("0");
        int insert = roleMapper.insertRole(sysRole1);
        if (1 == insert) {
//            //保存角色关联部门信息
//            SysRoleDept sysRoleDept = new SysRoleDept();
//            sysRoleDept.setRoleId(sysRole1.getRoleId());
//            sysRoleDept.setDeptId(rq.getDeptId());
//            int insert1 = roleDeptMapper.insert(sysRoleDept);
//            if (1 == insert1){
//                return R.ok();
//            }else {
//                return R.fail("新增角色信息失败");
//            }
            return true;
        } else {
            return false;
        }
    }

    /**
     * 商家端-角色启用禁用
     * @param roleId
     * @return
     */
    @Override
    public Object updateStatus(Long roleId) {
        SysRole sysRole = roleMapper.queryRoleById(roleId);
        if (ObjectUtils.isEmpty(sysRole)){
            throw new RuntimeException("没有查询到该角色");
        }
        String status = sysRole.getStatus();
        if ("0".equals(status)){
            status="1";
        }else{
            status="0";
        }
        sysRole.setStatus(status);
        sysRole.setUpdateBy(String.valueOf(SecurityUtils.getCompanyId()));
        int insert = roleMapper.updateRole(sysRole);
        if (1 == insert) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public List<Long> queryRoleByUserId(Long userId) {
        return roleMapper.queryRoleByUserId(userId);
    }
}
